package dominio;

import java.util.ArrayList;

/**
 * Created by Rafael Simon Garcia on 12/12/13.
 */
public class SwitchCostsCalculator {
    public static void CalculateCosts(ArrayList<Nodes> tasksList){
        ArrayList<Node> sourceElements, destinationElements, toRemove, toAdd, collision;
        ArrayList<Cost> costsList;
        for(Nodes task : tasksList){
            costsList = new ArrayList<>();
            for(Nodes next : tasksList){
                // get list of elements to remove SetA - SetB
                toRemove = removeSublistFromList(task.GetNodelist(), next.GetNodelist());

                //then get elements to add SetB - SetA
                toAdd = removeSublistFromList(next.GetNodelist(), task.GetNodelist());

                costsList.add(GetCostsFor(next.id, task.id, toRemove, toAdd));
            }
            task.SetCosts(costsList);
        }
    }


    private static Cost GetCostsFor(int nextId, int previousId, ArrayList<Node> r,  ArrayList<Node> a){
        int total = 0;
        if(previousId != nextId){
            //sum of elements to remove
            for(Node n : r) total += n.time;
            //sum of elements to add
            for(Node n : a) total += n.time;
        }

        //return the cost
        return new Cost(nextId, total);
    }

    private static ArrayList<Node> removeSublistFromList(ArrayList<Node> list, ArrayList<Node> sublist){
        ArrayList<Node> tmp = new ArrayList<>(list);
        for(Node n : sublist){
            if(listContainsNode(n, tmp)){
                tmp.remove(indexOfNodeInList(n, tmp));
            }
        }
        return tmp;
    }

    private static int indexOfNodeInList(Node n, ArrayList<Node> list){
        int length = list.size();
        for(int i =0; i< length; i++){
            if(list.get(i).name.equals(n.name))
            return i;
        }
        return -1;
    }

    private static boolean listContainsNode(Node n, ArrayList<Node> list){
        boolean result = false;
        for(Node listNode : list){
            if(listNode.name.equals(n.name)){
                result = true;
                break;
            }
        }
        return result;
    }
}
